const express = require('express')
const stu = require('../../students')
const router = express.Router()
router.get('/',(req,res)=>{
    // 读取所有学生信息
    stu.findAll((err, allStudents) => {
       if (err) {
           throw err
       }
       res.render('index',{students:allStudents})
   })
  
})

router.get('/students',(req,res)=>{
    let classID = req.query.classID
    stu.findStudnetsByClassID(classID,(err,students)=>{
        if(err){
            throw err
        }
        if(students){
            res.send(students)
        }else{
            res.send(`没有改班级学生${classID}`)
        }
    })
})

router.get('/add/student',(req,res)=>{
   res.render('new')
})
router.post('/addStudent',(req,res)=>{
   let newStudent = req.body
   stu.addStudent(JSON.stringify(newStudent), (err) => {
       if (err) {
           throw err
       }
       // 添加成功后，重定向到 /
       res.redirect('/')
   })
})

router.get('/update/student',(req,res)=>{
   let id = req.query.id
   stu.findStudentById(Number(id),(err,studnet)=>{
       if(err){
           throw err
       }
       res.render('update',{student:studnet})
   })
})

router.post('/updateStudent',(req,res)=>{
   let updateStudent = req.body
   stu.updateStudent(JSON.stringify(updateStudent),(err)=>{
       if(err){
           throw err
       }
       res.redirect('/')
   })
})

router.get('/delete/student',(req,res)=>{
   let id = req.query.id
   stu.deleteStudentById(Number(id),(err)=>{
       if(err){
           throw err
       }
       res.redirect('/')
   })
})
module.exports = router